from nicegui import ui
import plotly.graph_objects as go
import numpy as np

# 存储点的坐标
points = []

# 创建 Plotly 图表
fig = go.Figure()

# 初始化图表
fig.update_layout(
    title="Interactive Point Plot",
    xaxis_title="X Axis",
    yaxis_title="Y Axis",
    template="plotly_white"
)

# 定义更新图表的函数
def update_plot():
    global points

    # 清空图表数据
    fig.data = []

    if len(points) > 1:
        # 绘制连线
        x_values = [p[0] for p in points]
        y_values = [p[1] for p in points]
        fig.add_trace(go.Scatter(
            x=x_values,
            y=y_values,
            mode='lines+markers',
            name='Line',
            line=dict(color='blue'),
            marker=dict(size=10, color='red')
        ))
    elif len(points) == 1:
        # 只绘制单个点
        fig.add_trace(go.Scatter(
            x=[points[0][0]],
            y=[points[0][1]],
            mode='markers',
            name='Point',
            marker=dict(size=10, color='red')
        ))

    # 更新图表显示
    plot.update()

# 定义添加点的函数
def on_submit():
    try:
        x = float(x_input.value)
        y = float(y_input.value)
        points.append((x, y))  # 添加新点到列表
        update_plot()
    except ValueError:
        ui.notify("Please enter valid numbers for X and Y.", type='negative')

# 定义删除当前输入的点的函数
def on_delete():
    try:
        x = float(x_input.value)
        y = float(y_input.value)
        if (x, y) in points:
            points.remove((x, y))  # 从列表中删除该点
            update_plot()
        else:
            ui.notify("This point does not exist.", type='negative')
    except ValueError:
        ui.notify("Please enter valid numbers for X and Y.", type='negative')

# 创建 NiceGUI 页面布局
with ui.column().classes('items-center w-full'):
    ui.label("Interactive Point Plot with NiceGUI and Plotly").classes('text-2xl font-bold')

    # 输入框
    with ui.row():
        x_input = ui.input(label="X Coordinate", placeholder="Enter X value").classes('w-40')
        y_input = ui.input(label="Y Coordinate", placeholder="Enter Y value").classes('w-40')

    # 提交按钮
    ui.button("Add Point", on_click=on_submit).classes('bg-blue-500 text-white p-2 rounded')

    # 删除按钮
    ui.button("Delete This Point", on_click=on_delete).classes('bg-red-500 text-white p-2 rounded mt-2')

    # Plotly 图表
    plot = ui.plotly(fig).classes('w-full h-96')

# 启动应用
ui.run()
